package com.wfbi.security.chapter12.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wfbi.security.chapter12.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.PrintWriter;

/**
 * @author wfbi
 * @version 1.0
 * @date 2021/12/27 2:13 PM
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    /**
     * 采用不加密策略
     *
     * @author: wfbi
     * @date: 2021/12/27 2:18 PM
     * @return: org.springframework.security.crypto.password.PasswordEncoder
     **/
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 定义认证服务
     *
     * @param auth:
     * @author: wfbi
     * @date: 2021/12/27 2:17 PM
     * @return: void
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置忽略掉的 URL 地址，一般对于静态文件
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    /**
     * 权限配置
     *
     * @param http:
     * @author: wfbi
     * @date: 2021/12/27 2:23 PM
     * @return: void
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .and()
                .csrf().disable()
                .sessionManagement()
                .sessionFixation().migrateSession()
                .maximumSessions(1);
    }
}
